import requestUtil from '../../baseRequest.js'
import requestUrls from '../../requestUrl.js'
import { $Message } from '../../components/base/index'
import commonUtils from '../../utils/util.js'

let openId = wx.getStorageSync('openid')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userType: '',
    pageName: '',
    fromPage: '',
    openId,
    orderCenterId: '',
    publishSide: '',
    orderCenter: {},
    truckCenterList: [],
    orderCenterImageList: [],
    truckCenter: {},
    transportConfirmForm: {},
    goodsImages: [],
    disabled: true,
    deletable: false,
    otiId: '',

  },
  makePhoneCall(event) {
    const phoneNumber = event.currentTarget.dataset.phonenumber;
    commonUtils.callSomeBody(phoneNumber);
  },
  //车主申请运输货源
  linkToAddTruckCenter: function () {
    const { id } = this.data.orderCenter;
    wx.navigateTo({
      url: '/pages/truckCenter/add?orderCenterId=' + id + '&publishSide=' + this.data.publishSide
    })
  },
  //车主方取消申请运输此货物
  // cancelApplyOrderCenter: function () {
  //   const formData = {
  //     openId: this.data.openId,
  //     criteria: {
  //       publishSide: this.data.publishSide,
  //       truckCenterId: this.data.truckCenterId,
  //     }
  //   }
  //   requestUtil.postRequest(requestUrls.truckOrder.cancelApply, formData, (res) => {
  //     if (!res.hasError) {
  //       wx.showModal({
  //         title: '温馨提示',
  //         content: '操作成功',
  //         showCancel: false,
  //         success: res => {
  //           wx.switchTab({
  //             url: '/pages/homev2/index'
  //           })
  //         }
  //       })
  //     }
  //   })
  // },
  //查询委托单数据
  getById() {
    let formData = {};
    if (this.data.otiId) {
      formData = {
        openId: this.data.openId,
        criteria: {
          id: this.data.otiId,
        }
      }
    } else {
      formData = {
        openId: this.data.openId,
        criteria: {
          orderCenter: this.data.truckCenterId ? {} : {
            id: this.data.orderCenterId,
          },
          truckCenterId: this.data.truckCenterId,
          publishSide: this.data.publishSide,
        }
      }
    }
    let dateFormat = 'MM-dd hh';
    requestUtil.postRequest(requestUrls.truckOrder.getById, formData, (res) => {
      if (!res.hasError) {
        console.log(111);
        console.log(res);
        console.log(2222);
        const { orderCenter = {}, transportConfirmForm = {}, truckCenter = {}, publishSide} = res.result;
        this.setData({
          truckOrderInfoId: res.result.id,
          confirmId: res.result.confirmId,
        })
        const { orderTruckImageList = [], truckCenterList = [] } = orderCenter;
        if (orderTruckImageList && orderTruckImageList.length > 0) {
          let imageList = [];
          orderTruckImageList.forEach(image => {
            imageList.push({
              ...image,
              imageUrl: requestUrls.baseImagePrefixUrl + image.imageUrl,
            })
          })
          this.setData({
            orderCenterImageList: imageList,
            goodsImages: imageList,
          })
        }
        if (truckCenterList && truckCenterList.length > 0) {
          let truckList = [];
          truckCenterList.forEach(item => {
            truckList.push({
              ...item,
              freeBeginTime: commonUtils.formatDate(item.freeBeginTime, dateFormat),
              freeEndTime: commonUtils.formatDate(item.freeEndTime, dateFormat),
            })
          })
          this.setData({
            truckCenterList: truckList
          });
          if (this.data.publishSide === 'TRUCK_CENTER') {
            this.setData({
              truckCenterId: truckList[0].id
            });
          }
        }
        if (truckCenter) {
          this.setData({
            truckCenter
          })
        }
        if (transportConfirmForm) {
          this.setData({
            transportConfirmForm: {
              ...transportConfirmForm,
              packageDate: commonUtils.formatDate(transportConfirmForm.packageDate, dateFormat),
              receiverDate: commonUtils.formatDate(transportConfirmForm.receiverDate, dateFormat),
              createdTime: commonUtils.formatDate(transportConfirmForm.createdTime, dateFormat),
            }
          })
        }
        let statusName = '';
        let btnGroup = '';
        if(this.data.publishSide==='ORDER_CENTER'){
          if(orderCenter.statusId === '20'){
            if(!truckCenter){
              btnGroup = 'qxfb'
              statusName = '待确认';
            }else{
              btnGroup = 'sqz'
            }
          }
          if(orderCenter.statusId === '30'){
            btnGroup = 'sqz';
            statusName = '申请中';
          }

          if(orderCenter.statusId==='35'||orderCenter.statusId==='40'){
            statusName = orderCenter.statusName;
            btnGroup = 'sqz'
          }
          if(orderCenter.statusId === '60'){
            btnGroup = 'oysd';
            statusName = orderCenter.statusName;
          }
        }else if(this.data.publishSide==='TRUCK_CENTER'){
          if(orderCenter.statusId === '20'){
            if(!truckCenter){
              btnGroup = 'sqys'
            }else if(publishSide==='ORDER_CENTER'){
              statusName = '申请中';
              btnGroup = 'qxsq'
            } 
          }
          if(orderCenter.statusId === '30'){
            statusName = '待确认';
            btnGroup = 'hzjj';
          }
          if(orderCenter.statusId === '35'){
            statusName = orderCenter.statusName;
            btnGroup = 'dzh';
          }
          if(orderCenter.statusId === '40'){
            statusName = orderCenter.statusName;
            btnGroup = 'dxh';
          }
          if (orderCenter.statusId === '60') {
            statusName = '已送达';
            btnGroup = 'ysd';
          }
          if (orderCenter.statusId === '1000') {
            statusName = '已完成';
            btnGroup = 'ywc';
          }
        }
        // if (orderCenter.statusId === '20') {
        //   if (!truckCenter) {
        //     //货源已发布，不存在申请信息，查看方为车主，显示显示：申请运输
        //     if (this.data.publishSide === 'TRUCK_CENTER') {
        //       btnGroup = 'sqys'
        //     } else {
        //       //查看方为货主，按钮显示：取消发布
        //       btnGroup = 'qxfb'
        //     }
        //   }
        //   if (truckCenter && truckCenter.statusId === '30') {
        //     if (this.data.publishSide === 'TRUCK_CENTER') {
        //       statusName = '申请中';
        //       btnGroup = 'qxsq'
        //     } else {
        //       statusName = '待确认';
        //       btnGroup = 'hzjj';
        //     }
        //   }
        // }
        
        // if (orderCenter.statusId === '30') {
        //   if (this.data.publishSide === 'ORDER_CENTER') {
        //     statusName = '申请中';
        //     btnGroup = 'sqz'
        //   }
        //   if(this.data.publishSide === 'TRUCK_CENTER'){
        //     statusName = '待确认';
        //       btnGroup = 'hzjj';
        //   }
        // }

        // if (orderCenter.statusId === '35') {
        //   if (transportConfirmForm) {
        //     statusName = '待装货';
        //     btnGroup = 'dzh';
        //   }
        // }
        // if (orderCenter.statusId === '40') {
        //   if (transportConfirmForm && transportConfirmForm.step === 2) {
        //     statusName = '待卸货';
        //     btnGroup = 'dxh';
        //   }
        // }
        
        this.setData({
          statusName,
          btnGroup,
        })

        this.setData({
          orderCenter: {
            ...orderCenter,
            loadingBeginTime: commonUtils.formatDate(orderCenter.loadingBeginTime, dateFormat),
            loadingEndTime: commonUtils.formatDate(orderCenter.loadingEndTime, dateFormat),
          },
          //如果进入角色为货主，并且委托单信息不为空，则显示取消按钮；否则显示申请按钮
          showBtn: this.data.publishSide === 'TRUCK_CENTER' && this.data.truckCenterId ? 'cancel' : 'apply',
        })
      }
    })
  },
  cancelApplyOrderCenter() {
    wx.navigateTo({
      url: '/pages/orderCenter/cancelApply?publishSide=TRUCK_CENTER&truckCenterId=' + this.data.truckCenter.id,
    })
  },
  goodsLoading() {
    wx.navigateTo({
      url: '/pages/transportConfirm/stepTwo/index?truckOrderId=' + this.data.truckOrderInfoId + '&publishSide=' + this.data.publishSide
    })
  },
  goToComplain() {
    wx.navigateTo({
      url: '/pages/arbitration/create/index?publishSide=' + this.data.publishSide + "&transportConfirmFormId=" + this.data.confirmId
    });
  },
  goodsUnLoading() {
    wx.navigateTo({
      url: '/pages/transportConfirm/complete/index?confirmId=' + this.data.confirmId
    })
  },
  dealApply: function (event) {
    const optName = event.currentTarget.dataset.opt;
    const formData = {
      openId: this.data.openId,
      criteria: {
        orderCenterId: this.data.orderCenter.id,
        truckCenterId:this.data.truckCenter.id,
        //同意合作：传值Y;拒绝合作：传值N
        publishSide: this.data.publishSide || 'ORDER_CENTER',
        statusName: optName
      }
    }
    requestUtil.postRequest(requestUrls.truckOrder.dealOrReject, formData, (res) => {
      if (!res.hasError) {
        wx.showModal({
          title: '温馨提示',
          content: '操作成功',
          showCancel: false,
          success: res => {
            wx.switchTab({
              url: '/pages/homev2/index'
            })
          }
        })
      }
    })
  },
  confirmReceive: function (event) {
    const truckcenterid = event.currentTarget.dataset.truckcenterid;
    const formData = {
      openId: this.data.openId,
      criteria: {
        orderCenterId: this.data.orderCenterId,
        truckCenterId: truckcenterid,
      }
    }
    requestUtil.postRequest(requestUrls.orderCenter.confirmReceive, formData, (res) => {
      if (!res.hasError) {
        wx.showModal({
          title: '温馨提示',
          content: '操作成功',
          showCancel: false,
          success: res => {
            wx.switchTab({
              url: '/pages/homev2/index'
            })
          }
        })
      }
    })
  },
  showTruckInfo(event) {
    wx.navigateTo({
      url: '/pages/truckCenter/detail?publishSide=TRUCK_CENTER&otiId=' + this.data.truckOrderInfoId
    })

  },
  //跳转到运输单信息页面
  showDetail: function (event) {
    const id = event.currentTarget.dataset.truckcenterid;
    wx.navigateTo({
      url: '/pages/truckCenter/detail?truckCenterId=' + id + '&publishSide=' + this.data.publishSide
    })
  },
  previewImage(event) {
    const imageUrl = event.currentTarget.dataset.imgurl;
    wx.previewImage({
      urls: [imageUrl],
    })

  },
  //取消发布
  cancelOrder() {
    const formData = {
      openId: this.data.openId,
      criteria: {
        orderCenterId: this.data.orderCenterId,
        //同意合作：传值Y;拒绝合作：传值N
        publishSide: this.data.publishSide || 'ORDER_CENTER',
      }
    }
    requestUtil.postRequest(requestUrls.truckOrder.cancelOrder, formData, (res) => {
      if (!res.hasError) {
        wx.showModal({
          title: '温馨提示',
          content: '操作成功',
          showCancel: false,
          success: res => {
            wx.switchTab({
              url: '/pages/homev2/index'
            })
          }
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('货源详情传入参数：');
    console.log(options);
    const { orderCenterId = '', truckCenterId = '', publishSide = '', otiId = '' } = options;
    this.setData({
      orderCenterId: orderCenterId,
      truckCenterId: truckCenterId,
      publishSide: publishSide,
      otiId: otiId,
    });
    this.getById();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      path: '/pages/homev2/index'
    }
  }
})
